package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.common.Result;
import com.ruoyi.mapper.CustomerServiceMapper;
import com.ruoyi.service.CustomerServiceService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class CustomerServiceServiceImpl extends ServiceImpl<CustomerServiceMapper, CustomerService> implements CustomerServiceService {
    @Override
    public Result customerLogin(ReceptionCustomerService receptionCustomerService) throws UnsupportedEncodingException {
        //客服登录
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("root",receptionCustomerService.getRoot());
        CustomerService one = this.getOne(queryWrapper);
        if (one==null){
            Result result=new Result(501,"登录失败账号或密码错误","");
            return result;
        }
        if (!one.getRoot().equals(receptionCustomerService.getRoot())){
            Result result=new Result(501,"登录失败账号或密码错误","");
            return result;
        }
        //登录成功
        long l = System.currentTimeMillis() + (1000 * 60 * 60 * 24);
        String token = Jwts.builder().setId(one.getId() + "").setSubject(one.getName()).setIssuedAt(new Date()).setExpiration(new Date(l))
                .signWith(SignatureAlgorithm.HS256, "yang").compact();
        Map map=new HashMap();
        map.put("name",one.getName());
        map.put("receptNum",one.getReceptnum());
        map.put("token",token);
        map.put("sendId",one.getIsservice());
        Result result=new Result(200,"成功",map);
        return result;
    }

    @Override
    public Result customerOne(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims yang = Jwts.parser().setSigningKey("yang").parseClaimsJws(token).getBody();
        String id = yang.getId();
        CustomerService byId = this.getById(id);
        if (byId==null){
            Result result=new Result(500,"用户不存在","");
            return result;
        }
        Result result=new Result(200,"成功",byId);
        return result;
    }

    @Override
    public Result updateName(Integer id,String name) {
        CustomerService byId = this.getById(id);
        byId.setName(name);
        this.updateById(byId);
        Result result=new Result(200,"成功","");
        return result;
    }

    @Override
    public Result updateNumber(Integer id, Integer num) {
        CustomerService byId = this.getById(id);
        byId.setReceptnum(num);
        this.updateById(byId);
        Result result=new Result(200,"成功","");
        return result;
    }
}
